import time
from yt_download import get_mp3_from_ut, get_info_yt_video
from mp3tag import tag_mp3_file
from config import FEED_UPDATE_INTERVAL, is_suitable_video
from feed import CheckFeed
from database import DbClass
from agent import send_audio

# import subprocess
# subprocess.call(["python3", "bot.py"])

downloaded_videos = DbClass()

yt_feed = CheckFeed()
while True:
    videos = yt_feed.read()
    video = videos[0]
    video_id = video['yt_videoid']
    if is_suitable_video(video['title']) and downloaded_videos.is_not_downloaded(video_id):

        while get_info_yt_video(video['link'])['is_live']:
            print('This stream is on. Waiting for end')
            time.sleep(30 * 60)

        print("Start Downloading")
        mp3 = get_mp3_from_ut(video)
        if mp3:
            # title = mp3['title']
            tag_mp3_file(mp3)
            downloaded_videos.add_item(video_id)
            file_name = f"{mp3['title']}-{mp3['id']}.mp3"
            print(f"----DONE!\n----File name: {file_name}")
            send_audio(file_name)

    print(f"Next check after {FEED_UPDATE_INTERVAL} minutes")
    time.sleep(FEED_UPDATE_INTERVAL * 60)
